<?php

namespace Modules\Queue\Controllers;

use Modules\Queue\Library\Queue;
use Modules\Core\Models\Log;
use Core\Mvc\Controller;

class IndexController extends Controller
{
    public static $queue;

    public function indexAction()
    {
        ini_set('disable_functions', '');//开启所有函数
        ignore_user_abort(true); // 后台运行
        set_time_limit(0); // 取消脚本运行时间的超时上限
        error_reporting(0);
        set_error_handler([$this, 'errorHandler']);
        register_shutdown_function([$this, 'fatalErrorHandler']);
        //sleep(1);
        //self::$variables['#templates'] = 'fuwu';
        //$this->view->disable();
        if($this->request->getServerAddress() != $this->request->getClientAddress()){
            exit(1);
        }

        $queue = new Queue();
        if ($queue->isStart() == false) {
            $queue->run();
        }
        //throw new \Exception('sssss');
    }

    public function errorHandler($type, $message, $file, $line)
    {
        $errorString = '';
        if (self::$queue) {
            $errorString = '执行队列时出错，任务类型：' . self::$queue->task . ' 任务ID：' . self::$queue->getId();
        }
        $errorString .= $type . ' ' . $message . ' ' . $file . ' ' . $line;

        if (self::$queue) {
            self::$queue->error($errorString);
        } else {
            Log::add([
                'data' => $errorString,
                'type' => 'queue',
                'level' => 'warning'
            ]);
        }
        echo $errorString;
        if (file_exists(CACHE_DIR . 'queue/lock')) {
            @unlink(CACHE_DIR . 'queue/lock');
        }
    }

    //捕获fatalError
    public function fatalErrorHandler()
    {
        $e = error_get_last();
        //@unlink(CACHE_DIR . 'queue/lock');
        switch ($e['type']) {
            case E_ERROR:
            case E_PARSE:
            case E_CORE_ERROR:
            case E_COMPILE_ERROR:
            case E_USER_ERROR:
                $this->errorHandler($e['type'], $e['message'], $e['file'], $e['line']);
                break;
        }
    }
}
